package com.yys.gulimall.search.service.impl;/*
 * @author zq
 */

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yys.common.to.es.SkuEsTo;
import com.yys.gulimall.search.config.ElasticConfig;
import com.yys.gulimall.search.constant.EsConstant;
import com.yys.gulimall.search.service.MallSearchService;
import com.yys.gulimall.search.vo.SearchParam;
import com.yys.gulimall.search.vo.SearchResult;
import lombok.extern.log4j.Log4j2;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Log4j2
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public SearchResult search(SearchParam searchParam) {

        //准备检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParam);

        SearchResult result = null;

        try {
            //执行局检索请求
            SearchResponse response = restHighLevelClient.search(searchRequest, ElasticConfig.COMMON_OPTIONS);
            // 分析结果封装
            result = buildSearchResult(searchParam,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 准备检索请求
     * 需要考虑一下
     * 模糊匹配 过滤(属性,分类,品牌,价格区间,库存),排序,分页,高亮,聚合分析
     * */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        SearchSourceBuilder source = new SearchSourceBuilder();
        // TODO 匹配过滤聚合查询
        // 查询模糊匹配 过滤(属性,分类,品牌,价格区间,库存)
        // 1 构建bool query
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 1.1 must 模糊匹配 根据请求参数是否有keyword
        if(StringUtils.isNotBlank(searchParam.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }
        // 1.2.1 filter 按照三级分类过滤
        if(ObjectUtils.isNotNull(searchParam.getCatalog3Id())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",searchParam.getCatalog3Id()));
        }
        // 1.2.2 filter 按照品牌id过滤
        if(ObjectUtils.isNotEmpty(searchParam.getBrandId())) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }
        // 1.2.3 filter 按照属性attrs过滤
        if(ObjectUtils.isNotEmpty(searchParam.getAttrs())) {
            // 嵌入式query  attrs=1_安卓:其他&attrs=2_安卓_5G
            searchParam.getAttrs().forEach(attrStr -> {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String attrId = s[0]; // 检索属性id
                String[] attrValue = s[1].split(":"); // 检索属性值
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValue));
                // 每一个都是一个nested查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            });
        }

        // 1.2.4 filter 按照是否有库存过滤
        if(ObjectUtils.isNotNull(searchParam.getHasStock())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",searchParam.getHasStock() == 1));
        }

        // 1.2.5 filter 按照价格区间 1_500,_500,500_
        if(StringUtils.isNotBlank(searchParam.getSkuPrice())) {
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            String[] s = searchParam.getSkuPrice().split("_");
            if(s.length == 2) {
                rangeQueryBuilder.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                if(searchParam.getSkuPrice().startsWith("_")) {
                    rangeQueryBuilder.lte(s[0]);
                }
                if(searchParam.getSkuPrice().endsWith("_")) {
                    rangeQueryBuilder.gte(s[0]);
                }
            }
            boolQueryBuilder.filter(rangeQueryBuilder);
        }


        //封装所有查询条件
        source.query(boolQueryBuilder);

        //2. 排序,分页,高亮

        // 2.1 排序
        if(StringUtils.isNotBlank(searchParam.getSort())) {
            //sort=hotScore_acs/desc
            String sort = searchParam.getSort();
            String[] s = sort.split("_");
            SortOrder order = "ASC".equalsIgnoreCase(s[1]) ?SortOrder.ASC:SortOrder.DESC;
            source.sort(s[0], order);
        }

        // 2.2 分页
        // from 是开始位置 pageNum是页码需要换算
        source.from((searchParam.getPageNum() - 1) * EsConstant.PRODUCT_PAGE_SIZE);
        source.size(EsConstant.PRODUCT_PAGE_SIZE);

        // 2.3 高亮
        if(StringUtils.isNotBlank(searchParam.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            source.highlighter(highlightBuilder);
        }

        // 2.4聚合分析
        //2.4.1 聚合品牌信息
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);

        // 2.4.1.1 子聚合 品牌名字
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        // 2.4.1.2 子聚合 品牌图片
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));

        source.aggregation(brand_agg);

        //2.4.2 聚合分类信息
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        //2.4.2.1 分类子聚合 聚合名字
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName")).size(1);

        source.aggregation(catalog_agg);

        //2.4.3 属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        //2.4.3.1 自聚合attragg id
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        //2.4.3.1.1 自聚合name
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        //2.4.3.1.1 自聚合value
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));

        attr_agg.subAggregation(attr_id_agg);
        source.aggregation(attr_agg);

        // 测试一下dsl语句
        log.info("dsl语句:{}",source.toString());

        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, source);
    }

    /**
     * 封装检索结果
     * */
    private SearchResult buildSearchResult(SearchParam searchParam,SearchResponse searchResponse) {
        SearchResult result = new SearchResult();
        SearchHits hits = searchResponse.getHits();
        // 1. 封装返回商品
        SearchHit[] products = hits.getHits();

        List<SkuEsTo> skuEsToList = Arrays.stream(products).map(item -> {
            String sourceAsString = item.getSourceAsString();
            SkuEsTo skuEsTo = JSON.parseObject(sourceAsString, SkuEsTo.class);
            // 封装高亮
            if(StringUtils.isNotBlank(searchParam.getKeyword())) {
                String skuTitle = item.getHighlightFields().get("skuTitle").getFragments()[0].string();
                skuEsTo.setSkuTitle(skuTitle);
            }
            return skuEsTo;
        }).collect(Collectors.toList());

        result.setProducts(skuEsToList);

        // ==============2 3 4 都是聚合信息==========
        // 2. 封装属性值
        ParsedNested attr_agg = searchResponse.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<SearchResult.AttrVo> attrVoList = attr_id_agg.getBuckets().stream().map(bucket -> {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            // 设置id
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);
            // 设置name
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            // 设置value
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValueList = attr_value_agg.getBuckets().stream()
                    .map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            attrVo.setAttrValue(attrValueList);
            return attrVo;
        }).collect(Collectors.toList());
        result.setAttrs(attrVoList);

        // 3. 封装品牌信息
        ParsedLongTerms brand_agg = searchResponse.getAggregations().get("brand_agg");
        List<SearchResult.BrandVo> brandVoList = brand_agg.getBuckets().stream().map(bucket -> {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            // 得到品牌id
            long brandId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);
            // 得到品牌名字
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            // 得到品牌图片
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);

            return brandVo;
        }).collect(Collectors.toList());
        result.setBrands(brandVoList);

        // 4. 分类信息
        ParsedLongTerms catalog_agg = searchResponse.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVoList = catalog_agg.getBuckets().stream().map(bucket -> {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            // 得到分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));

            // 得到分类名
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);

            return catalogVo;
        }).collect(Collectors.toList());

        result.setCatlogs(catalogVoList);
        // =========================================

        // 5. 分页信息 来源于param
        result.setPageNum(searchParam.getPageNum());
        // 总记录树
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        // 总页码 计算得到
        int totalPages = total % EsConstant.PRODUCT_PAGE_SIZE == 0
                ? (int) (total / EsConstant.PRODUCT_PAGE_SIZE) : (int) (total/EsConstant.PRODUCT_PAGE_SIZE) + 1;
        result.setTotalPages(totalPages);

        // 分页页码
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);


        return result;
    }

}
